package cn.edu.gdut.deepcode.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class SimpleGlobalLock {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private final String luaScript= """
             if redis.call('GET', KEYS[1]) == ARGV[1] then
                 return redis.call('DEL', KEYS[1])==1
             else
                 return false
             end
            """;

    public boolean tryLock(String key, Long threadId, Long expire, TimeUnit timeUnit){
        return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(
                key,
                String.valueOf(threadId),
                expire,
                timeUnit
                ));
    }
    public boolean unlock(String key,Long threadId){
        RedisScript<Boolean> redisScript = new DefaultRedisScript<>(luaScript, Boolean.class);
        return Boolean.TRUE.equals(redisTemplate.execute(redisScript, Collections.singletonList(key), threadId.toString()));
    }

}


